home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / source.exe / POSIX / GREP / GETOPT.C < prev    next >
C/C++ Source or Header  |  1992-10-05  |  2KB  |  104 lines

  1. /*
  2.     getopt.c
  3.  
  4.     modified public-domain AT&T getopt(3)
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <string.h>
  9.  
  10. #ifdef _POSIX_SOURCE
  11. # include <unistd.h>
  12. #else
  13. # define STDERR_FILENO 2
  14. typedef signed int ssize_t;
  15. # ifdef __STDC__
  16. extern ssize_t write (int __fildes, const void *__buf, size_t __nbyte);
  17. # else
  18. extern ssize_t write ();
  19. # endif
  20. #endif
  21.  
  22. int opterr = 1;
  23. int optind = 1;
  24. int optopt;
  25. char *optarg;
  26.  
  27. #ifdef __STDC__
  28. static void ERR (char **argv, char *s, char c)
  29. #else
  30. static void ERR (argv, s, c)
  31. char **argv, *s, c;
  32. #endif
  33. {
  34.     char errbuf[2];
  35.  
  36.     if (opterr)
  37.     {
  38.         errbuf[0] = c;
  39.         errbuf[1] = '\n';
  40.         (void) write(STDERR_FILENO, argv[0], strlen(argv[0]));
  41.         (void) write(STDERR_FILENO, s, strlen(s));
  42.         (void) write(STDERR_FILENO, errbuf, sizeof errbuf);
  43.     }
  44. }
  45.  
  46. #ifdef __STDC__
  47. int getopt (int argc, char **argv, const char *opts)
  48. #else
  49. int getopt (argc, argv, opts)
  50. int argc;
  51. char **argv, *opts;
  52. #endif
  53. {
  54.     static int sp = 1, error = (int) '?';
  55.     static char sw = '-', eos = '\0', arg = ':';
  56.     register char c, *cp;
  57.  
  58.     if (sp == 1)
  59.         if (optind >= argc || argv[optind][0] != sw
  60.         || argv[optind][1] == eos)
  61.             return EOF;
  62.         else if (strcmp(argv[optind], "--") == 0)
  63.         {
  64.             optind++;
  65.             return EOF;
  66.         }
  67.     c = argv[optind][sp];
  68.     optopt = (int) c;
  69.     if (c == arg || (cp = strchr(opts, c)) == NULL)
  70.     {
  71.         ERR(argv, ": illegal option - ", c);
  72.         if (argv[optind][++sp] == eos)
  73.         {
  74.             optind++;
  75.             sp = 1;
  76.         }
  77.         return error;
  78.     }
  79.     else if (*++cp == arg)
  80.     {
  81.         if (argv[optind][sp + 1] != eos)
  82.             optarg = &argv[optind++][sp + 1];
  83.         else if (++optind >= argc)
  84.         {
  85.             ERR(argv, ": option requires an argument - ", c);
  86.             sp = 1;
  87.             return error;
  88.         }
  89.         else
  90.             optarg = argv[optind++];
  91.         sp = 1;
  92.     }
  93.     else
  94.     {
  95.         if (argv[optind][++sp] == eos)
  96.         {
  97.             sp = 1;
  98.             optind++;
  99.         }
  100.         optarg = NULL;
  101.     }
  102.     return (int) c;
  103. }
  104.